<template>
  <div>
    <el-form label-width="120px">
      <el-form-item label="用户名">
        <el-input disabled v-model="user.email" />
      </el-form-item>
      <el-form-item label="用户名">
        <el-input v-model="user.name" />
      </el-form-item>

      <el-form-item label="头像">
        <el-upload
            :headers="headers"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :on-error="handleAvatarError"
            :action="BASE_API+'/api/file/uploadAvatar'"
            class="avatar-uploader"
        >
          <img v-if="user.picture" :src="user.picture" style="width: 500px;height: 500px">
          <i v-else class="el-icon-plus avatar-uploader-icon"/>
        </el-upload>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="update()">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {update} from '@/api/user'
import {getUserInfo} from "@/api/home";
import {getToken} from "@/utils/auth";

/**
 * 获取token用于头像上传
 */
const token=getToken()
export default {
  name: "UserInfo",
  data(){
    return{
      token:'',
      headers:{
        'X-Token': token,
      },
      user:{},
      // BASE_API: 'http://localhost:8000',
      BASE_API: 'https://hubujyjs.cn:8080',
    }
  },
  created() {

  },
  mounted() {
    this.getUserInfo()
  },
  methods:{
    getUserInfo(){
      getUserInfo().then(data=>{
        this.user=data.data
      })
    },
    // 上传成功回调
    handleAvatarSuccess(res) {
      // console.log(res)
      if (res.code === 200) {
        // console.log(res)
        this.user.picture = res.data
        console.log(this.user)
        // 强制重新渲染
        this.$forceUpdate()
      } else {
        this.$message.error('服务器错误')
      }
    },

    // 错误处理
    handleAvatarError() {
      this.$message.error('上传失败')
    },

    // 上传校验
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isLt2M
    },
    update() {
      update(this.user).then(() => {
        // 提示
        this.$message({
          type: 'success',
          message: '添加成功'
        })
        this.getUserInfo()
        //组件通信，更改右上角信息
        // this.$emit('update',this.user)
        this.bus.$emit('update', this.user)
      })
    }
  }
}
</script>

<style scoped>

</style>
